package com.qf.fmall2203.shopcart.service.impl;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2203.alipay.WxpayUtils;
import com.qf.fmall2203.introducepro.entity.Product;
import com.qf.fmall2203.introducepro.entity.ProductImg;
import com.qf.fmall2203.introducepro.service.IProductImgService;
import com.qf.fmall2203.introducepro.service.IProductService;
import com.qf.fmall2203.order.entity.OrderItem;
import com.qf.fmall2203.order.service.IOrderItemService;
import com.qf.fmall2203.orders.entity.Orders;
import com.qf.fmall2203.orders.service.IOrdersService;
import com.qf.fmall2203.prosku.entity.ProductSku;
import com.qf.fmall2203.prosku.service.IProductSkuService;
import com.qf.fmall2203.shopcart.entity.OrderVo;
import com.qf.fmall2203.shopcart.entity.ShoppingCart;
import com.qf.fmall2203.shopcart.mapper.ShoppingCartMapper;
import com.qf.fmall2203.shopcart.service.IShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 购物车  服务实现类
 * </p>
 *
 * @author CM
 * @since 2023-02-16
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @Autowired
    IProductService productService;

    @Autowired
    IProductImgService productImgService;

    @Autowired
    IProductSkuService productSkuService;

    @Autowired
    IOrdersService ordersService;

    @Autowired
    IOrderItemService orderItemService;


    /**
     * 显示购物车信息
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ShoppingCart> shopCartList(Integer userId) {

        //1.获取购物车信息通过userId
        List<ShoppingCart> idShopCart = list(new QueryWrapper<ShoppingCart>().eq("user_id", userId));

        //2.将List<ShoppingCart> ---> List<product_id>
        List<String> productIdList = idShopCart.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        //3.查询product表中product_id在productIdList里面的数据
        List<Product> products = productService.list(new QueryWrapper<Product>().in("product_id", productIdList));

        //4.挂图片为products
        populateImg(products);

        //4.1
        Map<String, Product> productList = products.stream().collect(Collectors.toMap( product -> product.getProductId(), product -> product));

        //5.查询product_sku中的信息通过productId
        List<ProductSku> productSkuList = productSkuService.list(new QueryWrapper<ProductSku>().in("product_id", productIdList));

        //5.1
        Map<String, ProductSku> productSkus = productSkuList.stream().collect(Collectors.toMap(productSku -> productSku.getSkuId(), productSku -> productSku));

        //6.遍历购物车添加属性
        for (ShoppingCart shoppingCart : idShopCart) {

            //1.获取商品id
            String productId = shoppingCart.getProductId();
            String skuId = shoppingCart.getSkuId();


            shoppingCart.setProductName(productList.get(productId).getProductName());

            shoppingCart.setProductImg(productList.get(productId).getImgs().get(0).getUrl());

            shoppingCart.setSkuName(productSkus.get(skuId).getSkuName());

            shoppingCart.setOriginalPrice(productSkus.get(skuId).getOriginalPrice());

            shoppingCart.setSellPrice(productSkus.get(skuId).getSellPrice());

            shoppingCart.setStock(productSkus.get(skuId).getStock());

        }

        return idShopCart;
    }

    @Override
    public List<ShoppingCart> account(Integer[] cids) {

        List<ShoppingCart> shoppingCarts = new ArrayList<>();

        for (Integer cid : cids) {
            //1.获取购物车信息通过userId
            ShoppingCart shopcart = getOne(new QueryWrapper<ShoppingCart>().eq("cart_id", cid));
            shoppingCarts.add(shopcart);
        }

        //2.将List<ShoppingCart> ---> List<product_id>
        List<String> productIdList = shoppingCarts.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        //3.查询product表中product_id在productIdList里面的数据
        List<Product> products = productService.list(new QueryWrapper<Product>().in("product_id", productIdList));

        //4.挂图片为products
        populateImg(products);

        //4.1
        Map<String, Product> productList = products.stream().collect(Collectors.toMap( product -> product.getProductId(), product -> product));

        //5.查询product_sku中的信息通过productId
        List<ProductSku> productSkuList = productSkuService.list(new QueryWrapper<ProductSku>().in("product_id", productIdList));

        //5.1
        Map<String, ProductSku> productSkus = productSkuList.stream().collect(Collectors.toMap(productSku -> productSku.getSkuId(), productSku -> productSku));

        //6.遍历购物车添加属性
        for (ShoppingCart shoppingCart : shoppingCarts) {

            //1.获取商品id
            String productId = shoppingCart.getProductId();
            String skuId = shoppingCart.getSkuId();


            shoppingCart.setProductName(productList.get(productId).getProductName());

            shoppingCart.setProductImg(productList.get(productId).getImgs().get(0).getUrl());

            shoppingCart.setSkuName(productSkus.get(skuId).getSkuName());

            shoppingCart.setOriginalPrice(productSkus.get(skuId).getOriginalPrice());

            shoppingCart.setSellPrice(productSkus.get(skuId).getSellPrice());

            shoppingCart.setStock(productSkus.get(skuId).getStock());

        }

        return shoppingCarts;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public HashMap<String, Object> addOrder(Orders orders, Integer[] cids) throws Exception {

        //1.
        OrderItem orderItem = new OrderItem();

        //2查询订单库存是否充足

        List<ShoppingCart> shoppingCarts = list(new QueryWrapper<ShoppingCart>().in("cart_id", cids));

        //3将List<ShoppingCart> --> List<sku_id>
        List<String> skuIdList = shoppingCarts.stream().map(ShoppingCart::getSkuId).collect(Collectors.toList());
        List<String> productIdList = shoppingCarts.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        //4查询sku表信息
        List<ProductSku> skuList = productSkuService.list(new QueryWrapper<ProductSku>().in("sku_id", skuIdList));
        //5转
        Map<String, ProductSku> skuMap = skuList.stream().collect(Collectors.toMap(ProductSku::getSkuId, productSku -> productSku));

        for (ShoppingCart shoppingCart : shoppingCarts) {
            String skuId = shoppingCart.getSkuId();
            ProductSku productSku = skuMap.get(skuId);
            Integer stock = productSku.getStock();
            Integer cartnums = Integer.valueOf(shoppingCart.getCartNum());
            if(stock > cartnums){
                break;
            }else {
                throw new Exception("库存不足！！！");
            }
        }

        //6.将订单加入数据库orders
        String orderId = RandomUtil.randomNumbers(19);
        String orderItemId = RandomUtil.randomNumbers(19);
        orders.setOrderId(orderId);
        ordersService.save(orders);

        //7.查询product表信息
        List<Product> productList = productService.list(new QueryWrapper<Product>().in("product_id", productIdList));
        Map<String, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getProductId, p -> p));

        populateImg(productList);

        //8.将数据保存到orderItem中
        String productName = "";

        for (ShoppingCart shoppingCart : shoppingCarts) {

            String skuId = shoppingCart.getSkuId();
            String productId = shoppingCart.getProductId();
            String cartNum = shoppingCart.getCartNum();

            productName = productMap.get(productId).getProductName();
            List<ProductImg> imgs = productMap.get(productId).getImgs();
            for (ProductImg img : imgs) {
                if(img.getIsMain().equals(1)){
                    orderItem.setProductImg(img.getUrl());
                    break;
                }
            }
            //String proImg = productMap.get(productId).getImgs().get(0).getUrl();
            String skuName = skuMap.get(skuId).getSkuName();
            Integer stock = skuMap.get(skuId).getStock();
            Integer sellPrice = skuMap.get(skuId).getSellPrice();
            orderItem.setProductPrice(BigDecimal.valueOf(sellPrice));
            orderItem.setSkuName(skuName);
            orderItem.setProductName(productName);
            orderItem.setTotalAmount(BigDecimal.valueOf(orders.getActualAmount()));
            orderItem.setSkuId(skuId);
            orderItem.setProductId(productId);
            orderItem.setOrderId(orderId);
            orderItem.setItemId(orderItemId);
            orderItem.setBuyCounts(Integer.valueOf(cartNum));

            orderItemService.save(orderItem);
        }

        //删除购物车中的数据cids
        List<Integer> list = Arrays.asList(cids);
        removeByIds(list);


        HashMap<String, Object> map = new HashMap<>();
        map.put("orderId",orderId);
        map.put("productNames",productName);
        String payUrl = WxpayUtils.getPayUrl(orderId);
        map.put("payUrl",payUrl);

        return map;
    }


    private void populateImg(List<Product> products) {

        //1. list<Product> ---> list<ID>

        List<String> idList = products.stream().map(Product::getProductId).collect(Collectors.toList());

        //2.查询商品图片信息

        List<ProductImg> imgList = productImgService.list(new QueryWrapper<ProductImg>().in("item_id", idList));

        //3.List<ProductImg>  --->  MAP<ItemID,List<ProductImg>>

        Map<String, List<ProductImg>> imgMap = imgList.stream().collect(Collectors.groupingBy(ProductImg::getItemId));

        //4.把图片挂到商品中
        products.forEach(product -> {
            String productId = product.getProductId();

            List<ProductImg> productImgs = imgMap.get(productId);

            if(productImgs==null){
                //商品没有关联的图片信息，为了给前端反数据返回[]而不是返回null
                productImgs = new ArrayList<>();
            }

            product.setImgs(productImgs);
        });
    }

}
